//
//  HMUserAccountViewModel.swift
//  Faner_Weibo
//
//  Created by 范英强 on 16/1/29.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {
    
    var userAccount: HMUserAccount?
    
    //判断accountToken
    var accountToken:String? {
        if let accountToken = userAccount?.access_token where !isExpires{
            //判断是否过期
            return accountToken
        }
        return nil
    }
    //判断是否过期
    //true 代表过期 反之未过期
    var isExpires: Bool{
        
        guard let expiresDate = userAccount?.expiresDate else {
            return true
        }
        //测试过期方法
        //let newDate = expiresDate.dateByAddingTimeInterval(1)
  
        if NSDate().compare(expiresDate) == NSComparisonResult.OrderedAscending {
            return false
        }
        
        return true
    }
    
    
    //归档接档路径
    let archiverPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
    //全局访问点
    static let sharedAccount: HMUserAccountViewModel = HMUserAccountViewModel()
    
    private override init() {
        //可选值的 因为该类初始化的时候 就已经分配内存空间了 你在super.init()以上不允许
        super.init()
        userAccount = loadUserAccount()
    }
}

extension HMUserAccountViewModel{
    
    // MARK: - 请求数据
    
    func loadAccessToken(code: String,complete:(isSuccess: Bool)->()){
        
        
        HMNetWorkTools.sharedTools.loadAccessToken(code) { (response, error) -> () in
            if error != nil{
                print("请求失败\(error)")
                complete(isSuccess: false)
                return
            }
            
            guard let dict =  response as? [String : AnyObject] else{
                print("不是一个字典")
                return
            }
            let account = HMUserAccount(dict: dict)
            self.userAccount = account
            self.loadUserInfo(account.access_token!, uid: account.uid!, complete: complete)
        }
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let params = [
//            "client_id" : APP_KEY,
//            "client_secret" : APP_SECRET,
//            "grant_type" : "authorization_code",
//            "code" : code,
//            "redirect_uri": REDIRECT_URL
//        ]
//        HMNetWorkTools.sharedTools.request(.POST, url: urlString, params: params) { (response, error) -> () in
//            
//        }
        
    }
    
    //请求用户的数据
    private func loadUserInfo(accessToken:String,uid:String,complete:(isSuccess: Bool)->()){
        
        HMNetWorkTools.sharedTools.loadUserInfo(accessToken, uid: uid) { (response, error) -> () in
            if error != nil{
                print("发送请求失败\(error)")
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String : AnyObject] else{
                print("不是一个字典")
                complete(isSuccess: false)
                return
            }
            self.userAccount?.avatar_large = dict["avatar_large"] as? String
            self.userAccount?.screen_name = dict["screen_name"] as? String
            self.saveAccount(self.userAccount!)
            complete(isSuccess: true)
            
        }
      
    }
}

extension HMUserAccountViewModel{
    //归档当前对象
    func saveAccount(useraccont:HMUserAccount){

        NSKeyedArchiver.archiveRootObject(useraccont, toFile: archiverPath)
        
    }
    
    func loadUserAccount() ->HMUserAccount? {
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(archiverPath) as? HMUserAccount
        return result
    }

}
